package org.loong.crypto.extension.utils;

import java.security.SecureRandom;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;

public class AlgorithmIdentifierFactory {

    private AlgorithmIdentifierFactory() {

    }

    /**
     * Create an AlgorithmIdentifier for the passed in encryption algorithm.
     *
     * @param encryptionOID OID for the encryption algorithm
     * @param random SecureRandom to use for parameter generation.
     * @return a full AlgorithmIdentifier including parameters
     * @throws IllegalArgumentException if encryptionOID cannot be matched
     */
    public static AlgorithmIdentifier generateEncryptionAlgID(ASN1ObjectIdentifier encryptionOID, SecureRandom random) throws IllegalArgumentException {
        if (encryptionOID.equals(NISTObjectIdentifiers.id_aes128_CBC) || encryptionOID.equals(NISTObjectIdentifiers.id_aes192_CBC)
                || encryptionOID.equals(NISTObjectIdentifiers.id_aes256_CBC) || encryptionOID.equals(GMObjectIdentifiers.sms4_cbc)) {
            byte[] iv = new byte[16];
            random.nextBytes(iv);
            return new AlgorithmIdentifier(encryptionOID, new DEROctetString(iv));
        } else if (encryptionOID.equals(PKCSObjectIdentifiers.des_EDE3_CBC)) {
            byte[] iv = new byte[8];
            random.nextBytes(iv);
            return new AlgorithmIdentifier(encryptionOID, new DEROctetString(iv));
        } else {
            return new AlgorithmIdentifier(encryptionOID, DERNull.INSTANCE);
        }
    }
}
